package cn.itcast.web.sevlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //获取请求中的method参数
            String method = request.getParameter("method");
            //需求：通过反射调用当前对象的指定方法
            /*1.获取字节码文件对象*/
            Class clazz = this.getClass();
            /*2.获取Method对象*/
            Method declaredMethod = clazz.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            /*3.暴力反射，提高*/
            declaredMethod.setAccessible(true);
            /*4.执行某个对象的方法,result的值可能是null，也可能有值*/
            Object result = declaredMethod.invoke(this, request, response);
            if(result!=null && !"".equals(result)){
                if(result instanceof String){
                    String page = (String)result;
                    if(page.startsWith("forward")){ //forward开头，表示需要转发
                        request.getRequestDispatcher("/"+page.substring(8)).forward(request,response);
                    }else if(page.startsWith("redirect")){ //以redirect开头，表示需要重定向
                        response.sendRedirect(super.getServletContext().getContextPath() +
                                "/"+page.substring(9));
                    }else if(page.startsWith("refresh:")){//以refresh开头,表示等待两秒后跳转
                        response.setHeader("Refresh","2;"+
                                super.getServletContext().getContextPath()+"/"+page.substring(8));
                    }else {//默认转发
                        request.getRequestDispatcher("/"+page).forward(request,response);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
